前言
相信對於 MVC 這知識,一定不陌生,所以今天會再分享 Core MVC 可以怎麼用一些功能
分享主軸
參考文章
https://learn.microsoft.com/en-us/aspnet/core/migration/mvc?view=aspnetcore-8.0
Visual Studio產生方式
指令產生方式
dotnet tool install -g dotnet-aspnet-codegenerator
dotnet add package Microsoft.VisualStudio.Web.CodeGeneration.Design
dotnet aspnet-codegenerator area Admin //Admin為要取的名稱
結果
Program.cs
//原來設定
app.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
//Area 設定
app.MapControllerRoute(
name: "areas",
pattern: "{area:exists}/{controller=Home}/{action=Index}/{id?}");
Controller
[Area("Admin")]
public class AdminUserController : Controller
{
public IActionResult Login()
{
return View();
}
}
結果
創建一個繼承自 ViewComponent 的類別,並實現 Invoke 或 InvokeAsync 方法
補充注意 : 類別需要 ViewComponent 結尾,並必須繼承 ViewComponent,也可以使用依賴注入
public class RecentPostsViewComponent : ViewComponent
{
private readonly IPostService _postService;
public RecentPostsViewComponent(IPostService postService)
{
_postService = postService;
}
public async Task<IViewComponentResult> InvokeAsync(int count)
{
var posts = await _postService.GetRecentPostsAsync(count);
return View(posts);
}
}
(如下範例,會存放於 Views/Shared/Components/RecentPosts/Default.cshtml )
@model IEnumerable<Post>
<ul>
@foreach (var post in Model)
{
<li>@post.Title</li>
}
</ul>
@await Component.InvokeAsync("RecentPosts", new { count = 5 })
1. 預設路徑
Views/Shared/Components/{View Component Name}/{View Name}.cshtml //預設名稱為 Default.cshtml
2. 也可以將它放置與 Controller 相關的地方,如下
Views/{Controller Name}/Components/{View Component Name}/{View Name}.cshtml
注入 IConfiguration 物件
@inject IConfiguration Configuration
注入服務層服務
@inject IUserService UserService
<h1>User Service Example</h1>
<p>User Name: @UserService.GetUserName()</p>
參考文章
https://learn.microsoft.com/zh-tw/aspnet/core/mvc/overview?view=aspnetcore-8.0